# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
from random import choice
import requests
import json
import re
from twisted.internet import defer
from twisted.internet.error import TimeoutError, DNSLookupError, \
    ConnectionRefusedError, ConnectionDone, ConnectError, \
    ConnectionLost, TCPTimedOutError
from twisted.web.client import ResponseFailed
from scrapy.core.downloader.handlers.http11 import TunnelError


class MusicSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class MusicDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class RandomUserAgentAndProxyMiddlware(object):
    EXCEPTIONS_TO_RETRY = (defer.TimeoutError, TimeoutError, DNSLookupError,
                      ConnectionRefusedError, ConnectionDone, ConnectError,
                      ConnectionLost, TCPTimedOutError, ResponseFailed,
                      IOError, TunnelError)

    def  __init__(self, *args, **kwargs):
        self.user_agents = [
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
            "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
            "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
        ]
        self.proxies = []
        self.index = 0

    def get_proxy(self):
        # 使用讯代理付费api
        response = requests.get('http://api.xdaili.cn/xdaili-api//greatRecharge/getGreatIp?spiderId=76d4b0450ba84405ad79efe8f9859903&orderno=YZ20195258380Y1AsVU&returnType=2&count=10')
        json_proxy = json.loads(response.content)
        if json_proxy['ERRORCODE'] == '0':
            for element in json_proxy['RESULT']:
                proxy_ip = element['ip']
                proxy_port = element['port']
                proxy = ':'.join([proxy_ip, proxy_port])
                self.proxies.append('http://' + proxy)

    def get_free_proxy(self):
        return 'http://' + requests.get('http://localhost:5000/random').text

    def process_request(self, request, spider):
        request.headers['User-Agent'] = choice(self.user_agents)
        request.headers['referer'] = 'http://music.163.com'
        request.headers['host'] = 'music.163.com'
        request.headers['origin'] = 'https://music.163.com'
        request.headers['connection'] = 'keep-alive'
        # 代理列表为空，添加代理
        print('----中间件开始处理请求----')
        if len(self.proxies) == 0:
            # self.get_free_proxy()
            print('初始化代理')
            self.get_proxy()
        proxy = choice(self.proxies)
        print('使用的代理为：' + proxy)
        request.meta['proxy'] = proxy 
        print('中间件处理请求结束')
        return None

    def process_exception(self, request, exception, spider):
        #捕获重试异常
        if isinstance(exception, self.EXCEPTIONS_TO_RETRY):
            print('中间件开始处理异常')
            #在日志中打印异常类型
            print('产生的异常是: %s' % (exception))
            # 移除代理，发送请求时会添加新的代理
            proxy_banned = request.meta.get('proxy', False)
            # 如果被封禁的代理ip在列表中，则移除；如果不是，则说明是之前列表中的代理ip，直接删除即可
            if proxy_banned in self.proxies:
                self.proxies.remove(proxy_banned)
            print('被禁的代理是：' + proxy_banned)
            # 如果所有代理都被封了，获取新代理
            if len(self.proxies) == 0:
                self.get_proxy
            proxy = choice(self.proxies)
            print('要使用的新代理是：' + proxy)
            request.meta['proxy'] = proxy
            # del request.meta['proxy']
            print('----中间件处理异常结束----')
            return request
